//
//  NWHomeTableViewController.swift
//  微博01
//
//  Created by 牛威 on 15/12/12.
//  Copyright © 2015年 牛威. All rights reserved.
//

import UIKit
import SVProgressHUD

 /// 原微博的可重用标示符
let NWHomeTableCell = "NWHomeTableCell"

 /// 转发微博的可重用标示符
let NWHomeRetweedCellID  = "NWHomeRetweedsCellID"

class NWHomeTableViewController: NWVisitorTableViewController {
    

        //MARK: - 懒加载控件
    
    /// 懒加载视图模型对象
    
    private lazy var homeModelViewModel = HomeModelViewModel()
    
    /// 转场动画实现对象(遵守转场协议的对象)
    
    private lazy var pictureAnimator  = NWPictureAnimator()
    
    /**
     
     转场动画的实现逻辑
     1 NWPictureAnimator 定义了转场动画协议,并同时设置了三个方法,imageView,fromRect和toRect
      定义了转场代理属性和索引属性,这两个属性都是用来告诉被代理者实现具体动画的细节
     
     2 NWHomePictureView 遵守了转场动画协议
      原因:实现转场动画的所有细节,它是最清楚的
     
     3 NWHomeTableViewController,建立两者联系,它里面有一个cell,
       就直接告诉被代理者你要的在cell这里,你只需要知道它遵守了你的协议,有你要的素材,你要需要的时候找cell就ok
     
     
     */
    
    
        
        
        //MARK: - 设置nav的监听方法
        
        @objc  private  func searchFriends(){
            
            let vc = NWTempViewController()
            
            navigationController?.pushViewController(vc, animated: true)
            
            tabBarController?.tabBar.hidden = false
            
        }
        
        @objc  private  func pod(){
            
            print("pod")
            
        }
        
        
        
        
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            
            
            
            if !UserAccountViewModel.sharedAccount.isLogin {
                
                visitorView?.setVisitorViewInfo(nil, message:"最美的不是下雨天,而是与你一起发过微博的下午")
                
                return
                
            }
            
            setupUI()
            
            registerCell()

            loadData()
            
            //注册通知来接受查看照片的事件
            //循环引用 如果使用通知中心的block来监听 其中的self 一定要弱引用
            
            NSNotificationCenter.defaultCenter().addObserverForName(
                WBLookPhotoNotification,  //通知的KEY
                object: nil,               //发送通知的对象
                queue: nil)                 //如果在主队列为nil
                { [weak self](notify) -> Void in      //防止循环引用
                
                    guard let indexPath = notify.userInfo![WBLookPhotoIndexPathKEY] as? NSIndexPath else{
                    
                      return
                    
                    }
                    
                    guard let urls = notify.userInfo![WBLookPhotoURLsKEY] as? [NSURL] else{
                    
                      return
                    
                    }
                    
                    guard let cell = notify.object as? NWPictureAnimatorDelegate else {
                    
                        return
                    
                    }
                    
                    
                    let vc = NWPictureBrowserVC(indexPath: indexPath, urls: urls)
                    
                    
                    //MARK: - 自定义专场动画的实现
                    
                    //1 告诉系统modal 的类型是自定义类型 transition 专场
                    
                   vc.modalPresentationStyle = UIModalPresentationStyle.Custom
                    
                    //2 设置专场动画代理
                    
                    vc.transitioningDelegate = self?.pictureAnimator
                    
                    //3设置NWPictureAnimator的代理
                    
                    self?.pictureAnimator.setParams(cell, indexPath: indexPath, dismissDelegate: vc)
                    
                    //这种写法参数设置完全交给调用方,一旦调用方漏传参数,可能造成不必要的麻烦
//                    
//                    self?.pictureAnimator.dismissDelegate = vc
//                    self?.pictureAnimator.presentDelegate = cell
//                    self?.pictureAnimator.indexPath = indexPath
                    
                    self?.presentViewController(vc, animated: true, completion: nil)
                    
            }
            
            
            
            
        }
    
    //MARK: - 注销通知
    
    deinit {
    
     NSNotificationCenter.defaultCenter().removeObserver(self)
    
    
    }
        
        
        private func setupUI(){
            
            
            //设置左右上角的button
            
            navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "searchFriends")
            
            navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "pod")
            
            
        }
        
        //MARK: -  注册表格
        
        private func registerCell (){
            
            tableView.registerClass(NWHomeNormalCell.self, forCellReuseIdentifier: NWHomeTableCell)
            tableView.registerClass(NWHomeRetweedCell.self, forCellReuseIdentifier: NWHomeRetweedCellID)
            
            //预估行高
            
             tableView.estimatedRowHeight = 400
            
//            tableView.rowHeight = UITableViewAutomaticDimension
//            tableView.rowHeight = 400
            
            //设置分割线样式----在bottom和top之间有一个小重影
            
           self.tableView.separatorStyle = .None
            
            //测试下拉刷新 (下拉刷新控件默认没有,需要实例化)
            
             refreshControl = NWDownRefresh()
            
            
            refreshControl!.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
            
            
            //上拉刷新视图

            tableView.tableFooterView = pullUpView
            
            
            
            
        }
        
        
       @objc private func loadData(){
            
            refreshControl?.beginRefreshing()
            //关闭上啦刷新动画
            pullUpView.stopAnimating()
        
            homeModelViewModel.loadHomeModelData(isPullup: pullUpView.isAnimating()) { (isSuccessed) -> () in
                
                self.refreshControl?.endRefreshing()
                
                if !isSuccessed {
                    
                    SVProgressHUD.showInfoWithStatus("您的网络不给力请稍后重试...")
                    
                    
                    return
                }
                
                self.tableView.reloadData()
                
                
                
            }
            
        }
    
    
        //MARK: -  上拉刷新视图
    
    private lazy var pullUpView : UIActivityIndicatorView =  {
    
    
       let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        indicator.color = UIColor.lightGrayColor()

        return indicator
    
    }()
}



//MARK: - 实现数据源方法

extension NWHomeTableViewController {


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        //这里的arrayM在视图模型中写的是懒加载 失少要有数值 所以没有可选项判断
        
                return homeModelViewModel.arrayM.count
        
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        
        let array = homeModelViewModel.arrayM[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(array.cellID, forIndexPath: indexPath) as! NWHomeCell
        
        
        cell.arrayM = array
        
        //判断是否是最后一条微博
        
        if indexPath.row == homeModelViewModel.arrayM.count - 1 && !pullUpView.isAnimating() {
        
          pullUpView.startAnimating()
            
            //加载数据
            
            loadData()
        
            print("上拉刷新")
        
        }
        
        return cell
        
    }
    
    
   //代理方法 苹果官方文档指出:如果行高是固定值,就不要实现行高代理方法 这个方法调用次数过多,影响性能
    //实际开发中 行高一定要缓存
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
//        print("设置行高++++++\(indexPath)")
        //更新模型
        
        return  homeModelViewModel.arrayM[indexPath.row].rowHeight

        
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        print("点击cell")
        
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    
}


